<template>
  <div class="site-manage">
    <el-card>
      <div class="header">
        <span>站点管理</span>
        <el-button type="primary" @click="openSiteDialog('add')">新增站点</el-button>
        <el-button @click="openCategoryDialog" style="margin-left: 8px;">分类管理</el-button>
      </div>
      <el-form :inline="true" :model="filter" class="filter-bar" label-width="90px" style="margin-bottom: 16px;">
        <el-form-item label="站点名称">
          <el-input v-model="filter.name" placeholder="站点名称" clearable style="width: 140px;" />
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="filter.category" clearable style="width: 140px;">
            <el-option v-for="item in categoryOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filter.status" clearable style="width: 120px;">
            <el-option label="启用" value="启用" />
            <el-option label="禁用" value="禁用" />
          </el-select>
        </el-form-item>
        <div class="filter-actions-row">
          <el-button type="primary" @click="doFilter">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </div>
      </el-form>
      <el-table :data="tableData" style="width: 100%" :default-sort="{prop: 'sort', order: 'ascending'}">
        <el-table-column prop="logo" label="LOGO" width="80">
          <template #default="scope">
            <el-image :src="scope.row.logo" style="width: 40px; height: 40px; object-fit: contain;" fit="contain" />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="站点名称" width="140" />
        <el-table-column prop="code" label="站点编码" width="120" />
        <el-table-column prop="category" label="分类" width="120">
          <template #default="scope">
            <el-tag v-for="c in scope.row.category" :key="c" style="margin-right: 4px;">{{ c }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="url" label="官网" width="180">
          <template #default="scope">
            <el-link :href="scope.row.url" target="_blank">{{ scope.row.url }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="绑定账号数" width="120">
          <template #default="scope">
            <el-link type="primary" @click="goToAccountManage(scope.row.code)">
              {{ getAccountCount(scope.row.code) }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === '启用' ? 'success' : 'info'">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="desc" label="描述" min-width="180">
          <template #default="scope">
            <div class="desc-ellipsis">{{ scope.row.desc }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="showDetail(scope.row)">详情</el-button>
            <el-button size="small" @click="editSite(scope.row)">编辑</el-button>
            <el-button
              size="small"
              :type="scope.row.featured ? 'success' : 'primary'"
              @click="toggleFeatured(scope.row)"
            >
              {{ scope.row.featured ? '取消精选' : '设为精选' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="page.current"
        v-model:page-size="page.size"
        :total="page.total"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[10, 20, 50]"
        style="margin-top: 16px; text-align: right;"
      />
    </el-card>

    <!-- 新增/编辑站点弹窗 -->
    <el-dialog v-model="siteDialog.visible" :title="siteDialog.mode === 'add' ? '新增站点' : '编辑站点'" width="500px" :close-on-click-modal="false">
      <el-form :model="siteDialog.form" :rules="siteRules" ref="siteFormRef" label-width="100px" style="margin-top: 12px;">
        <el-form-item label="站点名称" prop="name">
          <el-input v-model="siteDialog.form.name" />
        </el-form-item>
        <el-form-item label="站点编码" prop="code">
          <el-input v-model="siteDialog.form.code" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="siteDialog.form.category" multiple clearable style="width: 100%">
            <el-option v-for="item in categoryOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="LOGO" prop="logo">
          <el-input v-model="siteDialog.form.logo" placeholder="图片URL（mock上传）" />
        </el-form-item>
        <el-form-item label="官网URL" prop="url">
          <el-input v-model="siteDialog.form.url" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="siteDialog.form.status" style="width: 100%">
            <el-option label="启用" value="启用" />
            <el-option label="禁用" value="禁用" />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="siteDialog.form.sort" :min="1" style="width: 100%" />
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input v-model="siteDialog.form.desc" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="siteDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitSite">保存</el-button>
      </template>
    </el-dialog>

    <!-- 站点详情弹窗 -->
    <el-dialog v-model="detailDialog.visible" title="站点详情" width="500px" :close-on-click-modal="false">
      <el-descriptions :column="1" border v-if="detailDialog.data">
        <el-descriptions-item label="站点名称">{{ detailDialog.data.name }}</el-descriptions-item>
        <el-descriptions-item label="站点编码">{{ detailDialog.data.code }}</el-descriptions-item>
        <el-descriptions-item label="分类">
          <el-tag v-for="c in detailDialog.data.category" :key="c" style="margin-right: 4px;">{{ c }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="LOGO">
          <el-image :src="detailDialog.data.logo" style="width: 60px; height: 60px; object-fit: contain;" fit="contain" />
        </el-descriptions-item>
        <el-descriptions-item label="官网">
          <el-link :href="detailDialog.data.url" target="_blank">{{ detailDialog.data.url }}</el-link>
        </el-descriptions-item>
        <el-descriptions-item label="绑定账号数">{{ getAccountCount(detailDialog.data.code) }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="detailDialog.data.status === '启用' ? 'success' : 'info'">{{ detailDialog.data.status }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="排序">{{ detailDialog.data.sort }}</el-descriptions-item>
        <el-descriptions-item label="描述">{{ detailDialog.data.desc }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialog.visible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 分类管理弹窗 -->
    <el-dialog v-model="categoryDialog.visible" title="分类管理" width="400px" :close-on-click-modal="false">
      <el-form :model="categoryDialog.form" ref="categoryFormRef" label-width="80px" @submit.prevent>
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryDialog.form.name" />
        </el-form-item>
      </el-form>
      <el-table :data="categoryDialog.list" style="margin-bottom: 12px;">
        <el-table-column prop="name" label="分类名称" />
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <div style="display: flex; gap: 8px;">
              <el-button size="small" @click="editCategory(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="deleteCategory(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="categoryDialog.visible = false">关闭</el-button>
        <el-button type="primary" @click="saveCategory">保存</el-button>
        <el-button @click="addCategory">新增分类</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, nextTick } from 'vue'
import { ElMessage, ElForm } from 'element-plus'
import { useRouter } from 'vue-router'

const categoryOptions = ref(['二手电商', '图书', '综合电商'])
const filter = reactive({ name: '', category: '', status: '' })
const allData = ref([
  { id: 'S001', name: '雅虎日拍', code: 'yahoo-auction', category: ['二手电商'], logo: 'https://logo.clearbit.com/auctions.yahoo.co.jp', url: 'https://auctions.yahoo.co.jp', status: '启用', sort: 1, desc: '日本最大二手拍卖平台', featured: false },
  { id: 'S002', name: '煤炉', code: 'mercari', category: ['二手电商'], logo: 'https://logo.clearbit.com/mercari.com', url: 'https://www.mercari.com/jp/', status: '启用', sort: 2, desc: '日本知名二手交易平台', featured: false },
  { id: 'S003', name: '雅虎闲置', code: 'yahoo-flea', category: ['二手电商'], logo: 'https://logo.clearbit.com/auctions.yahoo.co.jp', url: 'https://auctions.yahoo.co.jp/closedsearch', status: '禁用', sort: 3, desc: '雅虎二手闲置专区', featured: false },
  { id: 'S004', name: 'bookoff', code: 'bookoff', category: ['图书'], logo: 'https://logo.clearbit.com/bookoff.co.jp', url: 'https://www.bookoff.co.jp', status: '启用', sort: 4, desc: '日本大型二手书连锁', featured: false },
  // 新增站点
  { id: 'S005', name: 'Sofmap', code: 'sofmap', category: ['二手电商'], logo: '', url: 'https://www.sofmap.com', status: '启用', sort: 5, desc: 'Sofmap 日本电器商城', featured: false },
  { id: 'S006', name: 'SKiT', code: 'skit', category: ['二手电商'], logo: '', url: 'https://skit.ne.jp', status: '启用', sort: 6, desc: 'SKiT 官方商城', featured: false },
  { id: 'S007', name: 'Skitdolce', code: 'skitdolce', category: ['二手电商'], logo: '', url: 'https://skitdolce.jp', status: '启用', sort: 7, desc: 'Skitdolce 官方', featured: false },
  { id: 'S008', name: 'Tohoanima', code: 'tohoanima', category: ['二手电商'], logo: '', url: 'https://toho-anime.com', status: '启用', sort: 8, desc: 'Tohoanima 官方', featured: false },
  { id: 'S009', name: 'Kotobukiya', code: 'kotobukiya', category: ['二手电商'], logo: '', url: 'https://www.kotobukiya.co.jp', status: '启用', sort: 9, desc: 'Kotobukiya 官方', featured: false },
  { id: 'S010', name: 'JUMP SHO！', code: 'jumpsho', category: ['二手电商'], logo: '', url: 'https://jumpshop-online.com', status: '启用', sort: 10, desc: 'JUMP SHO！', featured: false },
  { id: 'S011', name: 'CCO', code: 'cco', category: ['二手电商'], logo: '', url: 'https://cco.com', status: '启用', sort: 11, desc: 'CCO 官方', featured: false },
  { id: 'S012', name: 'Store', code: 'store', category: ['二手电商'], logo: '', url: 'https://store.com', status: '启用', sort: 12, desc: 'Store 官方', featured: false },
  { id: 'S013', name: 'ANIPLEX+', code: 'aniplexplus', category: ['二手电商'], logo: '', url: 'https://www.aniplexplus.com', status: '启用', sort: 13, desc: 'ANIPLEX+ 官方', featured: false },
  { id: 'S014', name: 'm78', code: 'm78', category: ['二手电商'], logo: '', url: 'https://m-78.jp', status: '启用', sort: 14, desc: 'm78 官方', featured: false },
  { id: 'S015', name: 'Eeo', code: 'eeo', category: ['二手电商'], logo: '', url: 'https://eeo.today', status: '启用', sort: 15, desc: 'Eeo 官方', featured: false },
  { id: 'S016', name: 'Aniplexplus', code: 'aniplexplus2', category: ['二手电商'], logo: '', url: 'https://aniplexplus.jp', status: '启用', sort: 16, desc: 'Aniplexplus 官方', featured: false },
  { id: 'S017', name: 'Jumpcs', code: 'jumpcs', category: ['二手电商'], logo: '', url: 'https://jumpcs.com', status: '启用', sort: 17, desc: 'Jumpcs 官方', featured: false },
  { id: 'S018', name: 'ANIME', code: 'anime', category: ['二手电商'], logo: '', url: 'https://anime.com', status: '启用', sort: 18, desc: 'ANIME 官方', featured: false },
  { id: 'S019', name: 'AMNIBUS', code: 'amnibus', category: ['二手电商'], logo: '', url: 'https://amnibus.com', status: '启用', sort: 19, desc: 'AMNIBUS 官方', featured: false },
  { id: 'S020', name: 'Kjoanishop！', code: 'kyoanishop', category: ['二手电商'], logo: '', url: 'https://kyoanishop.com', status: '启用', sort: 20, desc: 'Kyoanishop 官方', featured: false },
  { id: 'S021', name: 'mOvIC', code: 'movic', category: ['二手电商'], logo: '', url: 'https://www.movic.jp', status: '启用', sort: 21, desc: 'Movic 官方', featured: false },
  { id: 'S022', name: 'AnimeCollection', code: 'animecollection', category: ['二手电商'], logo: '', url: 'https://anime-collection.jp', status: '启用', sort: 22, desc: 'AnimeCollection 官方', featured: false },
  { id: 'S023', name: 'Chara-Ani', code: 'chara_ani', category: ['二手电商'], logo: '', url: 'https://www.chara-ani.com', status: '启用', sort: 23, desc: 'Chara-Ani 官方', featured: false },
  { id: 'S024', name: 'Amnibus', code: 'amnibus2', category: ['二手电商'], logo: '', url: 'https://amnibus.jp', status: '启用', sort: 24, desc: 'Amnibus 官方', featured: false },
  { id: 'S025', name: 'Kyoanishop', code: 'kyoanishop2', category: ['二手电商'], logo: '', url: 'https://kyoanishop.jp', status: '启用', sort: 25, desc: 'Kyoanishop 官方', featured: false },
  { id: 'S026', name: 'Movic', code: 'movic2', category: ['二手电商'], logo: '', url: 'https://movic.jp', status: '启用', sort: 26, desc: 'Movic 官方', featured: false }
])
const page = reactive({ current: 1, size: 10, total: 0 })
const tableData = computed(() => {
  let data = allData.value
  if (filter.name) data = data.filter(row => row.name.includes(filter.name))
  if (filter.category) data = data.filter(row => row.category.includes(filter.category))
  if (filter.status) data = data.filter(row => row.status === filter.status)
  page.total = data.length
  const startIdx = (page.current - 1) * page.size
  return data.slice(startIdx, startIdx + page.size)
})

function doFilter() { page.current = 1 }
function resetFilter() { filter.name = ''; filter.category = ''; filter.status = ''; page.current = 1 }

const siteDialog = reactive({
  visible: false,
  mode: 'add' as 'add' | 'edit',
  form: { id: '', name: '', code: '', category: [], logo: '', url: '', status: '启用', sort: 1, desc: '', featured: false }
})
const siteFormRef = ref<InstanceType<typeof ElForm> | null>(null)
const siteRules = {
  name: [{ required: true, message: '请输入站点名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入站点编码', trigger: 'blur' }],
  category: [{ required: true, message: '请选择分类', trigger: 'change' }],
  logo: [{ required: true, message: '请填写LOGO图片URL', trigger: 'blur' }],
  url: [{ required: true, message: '请输入官网URL', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  sort: [{ required: true, message: '请输入排序', trigger: 'blur' }]
}
function openSiteDialog(mode: 'add' | 'edit', row?: any) {
  siteDialog.mode = mode
  if (mode === 'add') {
    Object.assign(siteDialog.form, { id: '', name: '', code: '', category: [], logo: '', url: '', status: '启用', sort: 1, desc: '', featured: false })
  } else if (row) {
    Object.assign(siteDialog.form, { ...row, featured: row.featured ?? false })
  }
  siteDialog.visible = true
  nextTick(() => siteFormRef.value?.clearValidate())
}
function editSite(row: any) {
  openSiteDialog('edit', row)
}
function submitSite() {
  siteFormRef.value?.validate((valid: boolean) => {
    if (!valid) return
    if (siteDialog.mode === 'add') {
      const newId = 'S' + (Math.floor(Math.random() * 9000) + 1000)
      allData.value.unshift({ ...siteDialog.form, id: newId, featured: siteDialog.form.featured ?? false })
      ElMessage.success('新增成功（mock）')
    } else {
      const idx = allData.value.findIndex(item => item.id === siteDialog.form.id)
      if (idx > -1) {
        allData.value[idx] = { ...siteDialog.form, featured: siteDialog.form.featured ?? false }
        ElMessage.success('编辑成功（mock）')
      }
    }
    siteDialog.visible = false
  })
}
function deleteSite(row: any) {
  allData.value = allData.value.filter(item => item.id !== row.id)
  ElMessage.success('删除成功')
}
function toggleStatus(row: any) {
  row.status = row.status === '启用' ? '禁用' : '启用'
  ElMessage.success('状态已更新')
}

const detailDialog = reactive({ visible: false, data: null as any })
function showDetail(row: any) {
  detailDialog.data = { ...row }
  detailDialog.visible = true
}

// 分类管理
const categoryDialog = reactive({
  visible: false,
  list: categoryOptions.value.map(name => ({ name })),
  form: { name: '' },
  editIndex: -1
})
const categoryFormRef = ref()
function openCategoryDialog() {
  categoryDialog.visible = true
  categoryDialog.form.name = ''
  categoryDialog.editIndex = -1
}
function addCategory() {
  if (!categoryDialog.form.name) return ElMessage.warning('请输入分类名称')
  if (categoryDialog.list.some(c => c.name === categoryDialog.form.name)) return ElMessage.warning('分类已存在')
  categoryDialog.list.push({ name: categoryDialog.form.name })
  categoryDialog.form.name = ''
  updateCategoryOptions()
  ElMessage.success('新增成功')
}
function editCategory(row: any) {
  categoryDialog.form.name = row.name
  categoryDialog.editIndex = categoryDialog.list.findIndex(c => c.name === row.name)
}
function saveCategory() {
  if (categoryDialog.editIndex > -1) {
    if (!categoryDialog.form.name) return ElMessage.warning('请输入分类名称')
    if (categoryDialog.list.some((c, i) => c.name === categoryDialog.form.name && i !== categoryDialog.editIndex)) return ElMessage.warning('分类已存在')
    categoryDialog.list[categoryDialog.editIndex].name = categoryDialog.form.name
    categoryDialog.editIndex = -1
    categoryDialog.form.name = ''
    updateCategoryOptions()
    ElMessage.success('修改成功')
  }
}
function deleteCategory(row: any) {
  categoryDialog.list = categoryDialog.list.filter(c => c.name !== row.name)
  updateCategoryOptions()
  ElMessage.success('删除成功')
}
function updateCategoryOptions() {
  categoryOptions.value = categoryDialog.list.map(c => c.name)
  // 清理站点分类中已被删除的分类
  allData.value.forEach(site => {
    site.category = site.category.filter((c: string) => categoryOptions.value.includes(c))
  })
}

function toggleFeatured(row: any) {
  row.featured = !row.featured
  if (row.featured) {
    ElMessage.success(`已将【${row.name}】设为精选`)
  } else {
    ElMessage.info(`已取消【${row.name}】的精选`)
  }
}

// 获取交易账号数据（mock，实际应从全局store或API获取）
import { tradeAccounts } from '@/mock/tradeAccounts'

const router = useRouter()
function getAccountCount(siteCode: string) {
  // 兼容code和AccountManage.vue的site字段映射
  // 例：yahoo-auction <-> yahoo_auction
  const code = siteCode.replace(/-/g, '_')
  return tradeAccounts.value.filter(acc => acc.site === code).length
}
function goToAccountManage(siteCode: string) {
  // 兼容code和AccountManage.vue的site字段映射
  const code = siteCode.replace(/-/g, '_')
  window.localStorage.setItem('accountManageActiveSiteTab', code)
  router.push('/settings/account')
}
</script>

<style scoped>
.site-manage { padding: 32px; }
.header { display: flex; gap: 12px; align-items: center; margin-bottom: 12px; }
.filter-bar { margin-bottom: 16px; }
.filter-actions-row { margin-top: 8px; display: flex; gap: 12px; }
.desc-ellipsis {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
  white-space: normal;
  line-height: 1.5;
  min-height: 3em;
  max-height: 3em;
}
</style> 